package com.keya.dicomtask;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Version 唯一生成器
 *
 * @author : xf.he
 * @version : 1.0 2023/11/17
 * @since : 1.0
 **/
@Service
public class VersionGenerator {

    private AtomicInteger version;

    @Resource
    DicomTaskService dicomTaskService;

    public synchronized Integer getVersion() {
        if (ObjectUtil.isEmpty(version)){
            QueryWrapper<DicomTask> wrapper = new QueryWrapper<>();
            wrapper.orderByDesc("version");
            wrapper.last("LIMIT 1");
            DicomTask one = dicomTaskService.getOne(wrapper);
            if (ObjectUtil.isNotEmpty(one)){
                version = new AtomicInteger(one.getVersion());
            }else {
                version = new AtomicInteger(1);
            }
        }
        return version.incrementAndGet();
    }

    private volatile boolean initialized = false;
    public Integer getVersion2() {
        if (!initialized) {
            synchronized (this) {
                if (!initialized) {
                    QueryWrapper<DicomTask> wrapper = new QueryWrapper<>();
                    wrapper.orderByDesc("version");
                    wrapper.last("LIMIT 1");
                    DicomTask one = dicomTaskService.getOne(wrapper);
                    if (one != null) {
                        version = new AtomicInteger(one.getVersion());
                    } else {
                        version = new AtomicInteger(1);
                    }
                    initialized = true;
                }
            }
        }
        return version.getAndIncrement();
    }
}
